#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
生产环境权限初始化脚本
基于开发环境的88个权限和8个角色重新创建权限体系
"""

import sys
sys.path.append('.')

from backend import create_app
from backend.infrastructure.database import db
from backend.models.role import Role
from backend.models.permission import Permission


def create_permissions_and_roles():
    """创建88个权限和8个角色，并进行角色权限分配"""
    
    app = create_app()
    with app.app_context():
        print("开始创建权限和角色体系...")
        
        # 1. 创建88个权限
        permissions_data = [
            ('audit:content', '内容审核'),
            ('audit:data_change', '数据变更审核'),
            ('audit:role_application', '角色申请审核'),
            ('chart:create', '创建图表'),
            ('chart:edit', '编辑图表'),
            ('chart:export', '导出图表'),
            ('chart:read', '查看图表'),
            ('data:all', '查看所有数据'),
            ('data:department', '查看部门数据'),
            ('data:export', '数据导出'),
            ('data:own_only', '仅查看自己数据'),
            ('feedback:export', '导出反馈数据'),
            ('feedback:read', '查看用户反馈'),
            ('feedback:reply', '回复用户反馈'),
            ('feedback:resolve', '处理反馈'),
            ('followup:create', '创建随访记录'),
            ('followup:delete', '删除随访记录'),
            ('followup:edit', '编辑随访记录'),
            ('followup:execute', '执行随访'),
            ('followup:read', '查看随访记录'),
            ('followup:schedule', '安排随访计划'),
            ('intervention:create', '创建干预记录'),
            ('intervention:delete', '删除干预记录'),
            ('intervention:edit', '编辑干预记录'),
            ('intervention:execute', '执行干预任务'),
            ('intervention:plan', '制定干预方案'),
            ('intervention:read', '查看干预记录'),
            ('intervention:review', '审核干预记录'),
            ('log:analyze', '日志分析'),
            ('log:export', '导出日志'),
            ('log:read', '查看操作日志'),
            ('medical_consult:create', '创建医生交流'),
            ('medical_consult:manage', '管理医生交流'),
            ('medical_consult:read', '查看医生交流'),
            ('medical_consult:reply', '回复医生交流'),
            ('miniprogram:access', '小程序基础访问'),
            ('miniprogram:feedback', '反馈建议'),
            ('miniprogram:intervention_view', '查看干预记录'),
            ('miniprogram:notification', '消息通知'),
            ('miniprogram:report_view', '查看报告'),
            ('miniprogram:student_bind', '学生绑定'),
            ('miniprogram:vision_view', '查看视力数据'),
            ('permission:create', '创建权限'),
            ('permission:delete', '删除权限'),
            ('permission:edit', '编辑权限'),
            ('permission:manage', '权限管理'),
            ('permission:read', '查看权限'),
            ('report:generate', '生成报告'),
            ('report:read', '查看报告'),
            ('report:schedule', '定时报告'),
            ('report:share', '分享报告'),
            ('report:template_manage', '报告模板管理'),
            ('role:create', '创建角色'),
            ('role:delete', '删除角色'),
            ('role:edit', '编辑角色'),
            ('role:manage', '角色管理'),
            ('role:permission_assign', '分配角色权限'),
            ('role:read', '查看角色'),
            ('social:comment', '评论互动'),
            ('social:create', '发布社交内容'),
            ('social:moderate', '内容审核'),
            ('social:read', '查看社交内容'),
            ('student:bind_manage', '学生绑定管理'),
            ('student:create', '创建学生档案'),
            ('student:delete', '删除学生档案'),
            ('student:edit', '编辑学生档案'),
            ('student:export', '导出学生数据'),
            ('student:import', '批量导入学生'),
            ('student:read', '查看学生档案'),
            ('system:backup', '数据备份'),
            ('system:config', '系统配置'),
            ('system:dict_manage', '字典管理'),
            ('system:manage', '系统管理'),
            ('system:monitor', '系统监控'),
            ('user:assign_role', '分配角色'),
            ('user:create', '创建用户'),
            ('user:delete', '删除用户'),
            ('user:edit', '编辑用户信息'),
            ('user:password_reset', '重置用户密码'),
            ('user:read', '查看用户信息'),
            ('user:role_assign', '分配用户角色'),
            ('user:status_manage', '用户状态管理'),
            ('vision:analyze', '视力数据分析'),
            ('vision:batch_import', '批量导入视力数据'),
            ('vision:create', '录入视力数据'),
            ('vision:delete', '删除视力数据'),
            ('vision:edit', '编辑视力数据'),
            ('vision:read', '查看视力数据'),
        ]
        
        print(f"创建 {len(permissions_data)} 个权限...")
        permissions = {}
        for code, name in permissions_data:
            permission = Permission(code=code, name=name)
            db.session.add(permission)
            permissions[code] = permission
        
        db.session.commit()
        print("✅ 权限创建完成")
        
        # 2. 创建8个角色
        roles_data = [
            ('admin', '系统超级管理员，拥有所有权限'),
            ('doctor', '医生角色，负责医疗相关功能'),
            ('teacher', '教师角色，负责学生管理和数据录入'),
            ('assistant', '助理角色，协助完成各项工作'),
            ('parent', '家长角色，查看自己孩子的相关信息'),
            ('registered_user', '已注册的普通用户'),
            ('guest', '访客用户，仅有基本查看权限'),
            ('测试角色1', '用于测试的角色'),
        ]
        
        print(f"创建 {len(roles_data)} 个角色...")
        roles = {}
        for name, description in roles_data:
            role = Role(name=name, description=description)
            db.session.add(role)
            roles[name] = role
        
        db.session.commit()
        print("✅ 角色创建完成")
        
        # 3. 角色权限分配
        print("开始角色权限分配...")
        
        # admin - 所有权限
        admin_permissions = list(permissions.values())
        for perm in admin_permissions:
            roles['admin'].permissions.append(perm)
        print(f"admin角色分配 {len(admin_permissions)} 个权限")
        
        # doctor - 医疗相关权限
        doctor_permission_codes = [
            'vision:read', 'vision:analyze', 'vision:create', 'vision:edit',
            'student:read', 'student:edit',
            'intervention:create', 'intervention:edit', 'intervention:read', 'intervention:plan', 'intervention:execute',
            'followup:create', 'followup:edit', 'followup:read', 'followup:schedule', 'followup:execute',
            'medical_consult:create', 'medical_consult:read', 'medical_consult:reply', 'medical_consult:manage',
            'report:read', 'report:generate',
            'chart:read', 'chart:create',
            'data:department', 'data:export',
        ]
        for code in doctor_permission_codes:
            if code in permissions:
                roles['doctor'].permissions.append(permissions[code])
        print(f"doctor角色分配 {len(doctor_permission_codes)} 个权限")
        
        # teacher - 教师相关权限
        teacher_permission_codes = [
            'student:create', 'student:read', 'student:edit', 'student:import', 'student:export',
            'vision:create', 'vision:read', 'vision:edit', 'vision:batch_import',
            'intervention:read', 'intervention:create', 'intervention:edit',
            'followup:read', 'followup:create', 'followup:edit',
            'report:read', 'report:generate',
            'chart:read',
            'data:department',
        ]
        for code in teacher_permission_codes:
            if code in permissions:
                roles['teacher'].permissions.append(permissions[code])
        print(f"teacher角色分配 {len(teacher_permission_codes)} 个权限")
        
        # assistant - 助理权限
        assistant_permission_codes = [
            'student:read', 'student:create', 'student:edit',
            'vision:read', 'vision:create', 'vision:edit',
            'intervention:read', 'intervention:create',
            'followup:read', 'followup:create',
            'report:read',
            'chart:read',
            'data:own_only',
        ]
        for code in assistant_permission_codes:
            if code in permissions:
                roles['assistant'].permissions.append(permissions[code])
        print(f"assistant角色分配 {len(assistant_permission_codes)} 个权限")
        
        # parent - 家长权限
        parent_permission_codes = [
            'miniprogram:access', 'miniprogram:vision_view', 'miniprogram:report_view',
            'miniprogram:intervention_view', 'miniprogram:notification', 'miniprogram:feedback',
            'miniprogram:student_bind',
            'vision:read', 'student:read', 'intervention:read', 'followup:read',
            'report:read', 'chart:read',
            'data:own_only',
        ]
        for code in parent_permission_codes:
            if code in permissions:
                roles['parent'].permissions.append(permissions[code])
        print(f"parent角色分配 {len(parent_permission_codes)} 个权限")
        
        # registered_user - 注册用户权限
        registered_user_permission_codes = [
            'miniprogram:access', 'miniprogram:vision_view', 'miniprogram:notification',
            'vision:read', 'student:read', 'report:read',
            'data:own_only',
        ]
        for code in registered_user_permission_codes:
            if code in permissions:
                roles['registered_user'].permissions.append(permissions[code])
        print(f"registered_user角色分配 {len(registered_user_permission_codes)} 个权限")
        
        # guest - 访客权限
        guest_permission_codes = [
            'miniprogram:access',
            'report:read',
            'chart:read',
        ]
        for code in guest_permission_codes:
            if code in permissions:
                roles['guest'].permissions.append(permissions[code])
        print(f"guest角色分配 {len(guest_permission_codes)} 个权限")
        
        # 测试角色1 - 基本权限
        test_role_permission_codes = [
            'vision:read', 'student:read', 'report:read',
            'data:own_only',
        ]
        for code in test_role_permission_codes:
            if code in permissions:
                roles['测试角色1'].permissions.append(permissions[code])
        print(f"测试角色1分配 {len(test_role_permission_codes)} 个权限")
        
        db.session.commit()
        print("✅ 角色权限分配完成")
        
        # 4. 验证结果
        print("\n=== 权限体系创建完成 ===")
        total_permissions = Permission.query.count()
        total_roles = Role.query.count()
        print(f"总权限数: {total_permissions}")
        print(f"总角色数: {total_roles}")
        
        print("\n角色权限分配情况:")
        for role_name, description in roles_data:
            role = Role.query.filter_by(name=role_name).first()
            if role:
                perm_count = role.permissions.count()
                print(f"  {role.name}: {perm_count} 个权限")


if __name__ == '__main__':
    create_permissions_and_roles()
